#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File    :   items.py
@Time    :   2023/04/19 21:03:40
@Author  :   Rico Chen 
@Mail    :   55059@qq.com
@Version :   1.0
@Desc    :   None
"""
import os
import sys

# 引入上一级或兄弟子目录的文件
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)

fp = sys.path.append(os.pardir)
from peewee import *
import datetime
from typing import Optional
import setting
import json
from tab_beian_detail import BeiAnDetail
from tab_beian import BeiAn,LastSpider
from db_pool import db,RetryMySQLDatabase

fn = os.getcwd() + "/tar.db"
db2 = SqliteDatabase(fn)
db2.connect()

class BaseModel2(Model):
    class Meta:
        database = db2

class TabBa(BaseModel2):
    id = BigAutoField()
    data_id = CharField(null=True)
    add_time = CharField(null=True)
    apply_organ = CharField(null=True)
    begin_date = DateField(null=True)
    expiry_date = DateField(null=True)
    finish_date = DateField(null=True)
    full_name = CharField(null=True)
    has_start = IntegerField(null=True)
    is_validity = CharField(null=True)
    note = CharField(null=True)
    over_date = DateField(null=True)
    place = CharField(null=True)
    project_name = CharField(null=True)
    proof_or_serial_code = CharField(null=True)
    scope = TextField(null=True)
    sfjz = CharField(null=True)
    state_flag_name = CharField(null=True)
    submit_date = CharField(null=True)
    total_invest = IntegerField(null=True)
    update_time = CharField(null=True)

    class Meta:
        table_name = "tab_ba"

def insert_from_dict(json_str: str):
    di = json.loads(json_str)
    p = TabBa()
    p.data_id = di["data"]["id"]
    p.add_time = di["data"]["addTime"]
    p.apply_organ = di["data"]["applyOrgan"]
    p.begin_date = di["data"]["beginDate"]
    p.expiry_date = di["data"]["expiryDate"]
    p.finish_date = di["data"]["finishDate"]
    p.full_name = di["data"]["fullName"]
    p.has_start = di["data"]["hasStart"]
    p.is_validity = di["data"]["isValidity"]
    p.note = di["data"]["note"]
    p.over_date = di["data"]["overDate"]
    p.place = di["data"]["place"]
    p.project_name = di["data"]["projectName"]
    p.proof_or_serial_code = di["data"]["proofOrSerialCode"]
    p.scope = di["data"]["scope"]
    p.sfjz = di["data"]["sfjz"]
    p.state_flag_name = di["data"]["stateFlagName"]
    p.submit_date = di["data"]["submitDate"]
    p.total_invest = di["data"]["totalInvest"]
    p.update_time = di["data"]["updateTime"]
    p.save()
    return True

# 检查是否有BeiAnDetail，BeiAnDetail，LastSpider这些表，没有即创建
def create_the_tables():
        with db.connection_context():
            db.connect(reuse_if_open=True)
            db.create_tables([BeiAnDetail])
            if not BeiAnDetail.table_exists():
                print("BeiAnDetail表不存在,创建中")
                db.create_tables([BeiAnDetail])
            
            if not BeiAn.table_exists():
                print("BeiAn表不存在,创建中")
                db.create_tables([BeiAn])

            if not LastSpider.table_exists():
                print("LastSpider表不存在,创建中")
                db.create_tables([LastSpider])

# 从sqlite中读取数据,写入mysql中
def write_from_sqlite():
    ts = []
    i = 0
    for p in TabBa.select():
        t = BeiAnDetail()
        t.id = p.data_id
        t.addTime =p.add_time 
        t.applyOrgan = p.apply_organ
        t.beginDate =  p.begin_date 
        t.expiryDate = p.expiry_date
        t.finishDate = p.finish_date 
        t.fullName = p.full_name 
        t.hasStart = p.has_start 
        t.isValidity = p.is_validity 
        t.note = p.note 
        t.overDate = p.over_date
        t.place = p.place 
        t.projectName = p.project_name 
        t.proofOrSerialCode = p.proof_or_serial_code
        t.scope = p.scope
        t.sfjz  = p.sfjz
        t.stateFlagName =p.state_flag_name 
        t.submitDate = p.submit_date 
        t.totalInvest = p.total_invest
        t.updateTime = p.update_time 
        i += 1
        ts.append(t)
        if i == 101:
            with db.atomic():
                BeiAnDetail.bulk_create(ts)
                print("update 100条记录")
            ts =[]
            i = 0
    with db.atomic():
        BeiAnDetail.bulk_create(ts,batch_size=i)
        print("update %d条记录"%i)


if __name__ == "__main__":
    create_the_tables()
    #with database.atomic():
    write_from_sqlite()
   